from rest_framework import serializers
from fdfs_client.client import Fdfs_client

from apps.goods.models import SKUImage, SKU


# 图片管理的序列化器
class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKUImage
        fields = '__all__'

    # 在这里重写，修改图片方法，同理新增图片一样可以在此处实现
    # def create(self, validated_data):
    #     pass

    # 重写ｕｐｄａｔｅ方法,与在视图修改不同，这里相当于修改局部代码，不是全部重写，减少冗余
    def update(self, instance, validated_data):
        # 1.实现Fdfs图片上传
        # 1.1 创建Fdsf实例
        cli = Fdfs_client('utils/fastdfs/client.conf')
        # 1.2 上传图片
        upload_image = validated_data.get('image')
        result = cli.upload_appender_by_buffer(upload_image.read())
        # 1.3 判断结果
        """
        'Remote file_id': 'group1/M00/00/00/wKjllF5IoHGAHgORAAJUduk8mU48823845',
        'Status': 'Upload successed.',
        """
        if result.get('Status') != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        file_id = result.get('Remote file_id')

        # 2.更新图片
        instance.image = file_id
        instance.save()
        return instance


# ＳＫＵ简单获取的序列化器
class SimpleSKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['id', 'name']
